//package cn.joeg.web.core.interceptor;
//
//import com.ecfront.dew.common.Resp;
//import com.ecfront.dew.common.interceptor.DewInterceptRespBody;
//import com.pubinfo.samantha.app.css.entity.KeyData;
//import com.pubinfo.samantha.app.css.entity.WidgetDef;
//import com.pubinfo.samantha.app.css.repository.WidgetDefRepository;
//import com.pubinfo.samantha.app.css.widget.core.vo.WidgetDataReq;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//
//import java.util.HashMap;
//import java.util.Map;
//import java.util.Spliterator;
//import java.util.Spliterators;
//import java.util.stream.Collectors;
//import java.util.stream.StreamSupport;
//
//@Component
//public class WidgetDefInterceptor extends WidgetDataFetchInterceptor {
//
//    public static final String WIDGET_DEF_CONTEXT = "widgetDef";
//
//    private static Map<String, WidgetDef> widgetDefs = new HashMap<>();
//
//    @Autowired
//    private WidgetDefRepository widgetDefRepository;
//
//    @Override
//    public Resp<DewInterceptRespBody<WidgetDataReq>> before(WidgetDataReq obj, Map<String, Object> context) {
//        if (widgetDefs.containsKey(obj.getWidgetCode())) {
//            return checkAndSet(obj, context);
//        }
//        WidgetDef widgetDef = widgetDefRepository.getByCode(obj.getWidgetCode());
//        if (widgetDef != null) {
//            widgetDefs.put(obj.getWidgetCode(), widgetDef);
//            return checkAndSet(obj, context);
//        } else {
//            return Resp.notFound(String.format("Code[%s]不存在", obj.getWidgetCode()));
//        }
//    }
//
//    private Resp<DewInterceptRespBody<WidgetDataReq>> checkAndSet(WidgetDataReq obj, Map<String, Object> context) {
//        WidgetDef widgetDef = widgetDefs.get(obj.getWidgetCode());
//        if (StreamSupport
//                .stream(Spliterators.spliteratorUnknownSize(obj.getArgs().fieldNames(), Spliterator.ORDERED), false)
//                .collect(Collectors.toList())
//                .containsAll(widgetDef.getKeyDataSet().stream().map(KeyData::getCode).collect(Collectors.toSet()))) {
//            context.put(WIDGET_DEF_CONTEXT, widgetDef);
//            return Resp.success(DewInterceptRespBody.build(obj, context));
//        } else {
//            return Resp.badRequest(String.format("Code[%s]缺少必要参数", obj.getWidgetCode()));
//        }
//    }
//
//    @Override
//    public Resp<DewInterceptRespBody<WidgetDataReq>> after(WidgetDataReq obj, Map<String, Object> context) {
//        return Resp.success(DewInterceptRespBody.build(obj, context));
//    }
//
//}
